package com.fanjia.es_demo.utils;

import com.fanjia.es_demo.entity.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @author fanjia
 * @className HtmlParseUtil
 * @description TODO
 * @date 2021/4/14 19:25
 */
public class HtmlParseUtil {

    /*public static void main(String[] args) throws IOException {
        List<Content> contentList = parseJD("java");
        contentList.forEach(System.out::println);
    }*/

    public static List<Content> parseJD(String keywords) throws IOException {
        String url = "https://search.jd.com/Search?keyword="+keywords;
        Document document = Jsoup.parse(new URL(url), 30000);
        Element j_goodsList = document.getElementById("J_goodsList");
        Elements elements = j_goodsList.getElementsByTag("li");
        List<Content> contentList = new ArrayList<>();
        for(Element element : elements){
            String img = element.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = element.getElementsByClass("p-price").eq(0).text();
            String title = element.getElementsByClass("p-name").eq(0).text();
            //System.out.println("===========================");
            //System.out.println(element.html());
            Content content = new Content();
            content.setImg(img);
            content.setPrice(price);
            content.setTitle(title);
            contentList.add(content);
        }
        return contentList;
    }





}
